import {reqCartList, reqDeletCartById, reqUpdateCheckedById} from '@/api/index'

const state ={
  cartList: []
}
const mutations = {
  GETCARTLIST(state, cartList) {
    state.cartList = cartList
  }
}
const actions = {
  // 获取购物车列表数据
  async getCartList({commit}) {
  let result = await reqCartList()
  if(result.code == 200) {
    commit('GETCARTLIST', result.data)
  }
  },
  // 删除某一个产品的操作
  async deleteCartListBySkuId({commit}, skuId) {
    let result = await reqDeletCartById(skuId)
    if(result.code == 200) {
      return 'ok'
    } else {
      return Promise.reject(new Error('faile'))
    }
  },
  // 切换购物车某一件商品的选中状态
  async updateCheckeById({commit},{skuId, isChecked}) {
    let result = await reqUpdateCheckedById(skuId, isChecked)
    if(result.code == 200) {
      return 'ok'
    } else {
      return Promise.reject(new Error('faile'))
    }
  },
  // 购物车中删除全部勾选的产品
  deleteAllCheckedCart({dispatch, getters}) {
    // context: 当前小仓库， commit：[提交mutations修改state]， getters:[计算属性]，dispatch:[派发action]，state: [当前仓库数据]
    // 获取购物车中的全部产品(是一个数组)
    let PromiseAll = []
    getters.cartList.cartInfoList.forEach(item => {
      let promise = item.isChecked == 1 ? dispatch('deleteCartListBySkuId', item.skuId) : ''
      // 将每一个返回的Promise添加到数组中
      PromiseAll.push(promise)
    });
    // 只有全部p1|p2......都成功，返回的结果即为成功，否则返回失败
    return Promise.all(PromiseAll)
  },
  // 修改全部产品的状态
  updateAllCartIsChecked({dispatch,state},isChecked) {
    // 数组
    let PromiseAll = []
    state.cartList.cartInfoList.forEach(item => {
      let promise = dispatch('updateCheckeById',{skuId:item.skuId, isChecked})
      PromiseAll.push(promise)
    })
    // 返回最终结果
    return Promise.all(PromiseAll)
  }
}
const getters = {
  cartList(state) {
    return state.cartList[0] || {}
  }
}

export default {
  state,
  mutations,
  actions,
  getters
}